package com.southwind.springboottest.study.Java中通讯.socket通讯;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
        int port = 12345; // 服务器端口

        try (ServerSocket serverSocket = new ServerSocket(port)) {
            System.out.println("Server is listening on port " + port);

            while (true) {
                // 接受客户端连接
                Socket socket = serverSocket.accept();
                System.out.println("Client connected");

                // 获取输入流和输出流
                InputStream input = socket.getInputStream();
                OutputStream output = socket.getOutputStream();

                // 创建输入流读取客户端消息
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                PrintWriter writer = new PrintWriter(output, true);

                // 读取客户端消息并回复
                String message = reader.readLine();
                System.out.println("Received: " + message);
                writer.println("Echo: " + message);

                // 关闭连接
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

